<?php

/**
 *    Desc
 *
 *    @author    Garbin
 *    @usage    none
 */
class MemberApp extends MemberbaseApp
{
    function index()
    {
		//会员资金管理=======================================
		$my_money_mod =& m('my_money');
		$money_money=$my_money_mod->getRow("select money,money_dj,rz_is_ok from {$my_money_mod->table} where user_id='{$this->visitor->get('user_id')}'");
		if(!$money_money){
			/*by:liangcaijian 帐户资金自动注册开通 开始******************************/
			$my_money_mod->add(array( 'user_id' => $this->visitor->get('user_id'), 'user_name' => $this->visitor->get('user_name'), 'add_time' => gmtime() ));	
		}
		$this->assign('money_money', $money_money);
		//会员资金管理=======================================
		
		//我的运单
		$kd_order_mod =& m('kd_order');
		$kd_yubao_mod =& m('kd_yubao');
		$kd_qujian_mod =& m('kd_qujian');
		$show_number = array(
		  'order'=>$kd_order_mod->getOne("SELECT COUNT(*) FROM {$kd_order_mod->table} WHERE user_id='{$this->visitor->get('user_id')}' "), 
		  'yubao'=>$kd_yubao_mod->getOne("SELECT COUNT(*) FROM {$kd_yubao_mod->table} WHERE user_id='{$this->visitor->get('user_id')}' AND baoguo > 0  "),
		  'qujian'=>$kd_qujian_mod->getOne("SELECT COUNT(*) FROM {$kd_qujian_mod->table} WHERE user_id='{$this->visitor->get('user_id')}'"),
		);	
		$this->assign('show_number', $show_number);
			
        /* 当前用户中心菜单 */
		$this->_config_seo('title', '会员中心 - ' . Conf::get('site_name'));
        $this->import_resource(array( 'style' =>  'res:style/css_member.css' ));
		$this->display('member.index.html');
    }


	/*****登录会员******/
    function login()
    {
        if ($this->visitor->has_login)
        {
            $this->show_warning('has_login');
            return;
        }
        if (!IS_POST)
        {
            if (!empty($_GET['ret_url']))
            {
                $ret_url = htmldecode($_GET['ret_url']);
            }else{
                if (isset($_SERVER['HTTP_REFERER']))
                {
                    $ret_url = $_SERVER['HTTP_REFERER'];
                }else{
                    $ret_url = site_url() . '/';
                }
            }
            /* 防止登陆成功后跳转到登陆、退出的页面 */
            $ret_url = strtolower($ret_url);            
            if (str_replace(array('act=login', 'act=logout',), '', $ret_url) != $ret_url)
            {
                $ret_url = site_url() . '/';
            }

            $this->import_resource('jquery.plugins/jquery.validate.js');
            $this->assign('ret_url', rawurlencode($ret_url));
            $this->_config_seo('title', '用户登录 - ' . Conf::get('site_name'));
			$this->assign('curitem', '用户登录');	
            $this->display('member.login.html');
        }
        else
        {
            $user_name = trim($_POST['user_name']);
            $password  = $_POST['password'];

            $ms =& ms();
            $user_id = $ms->user->auth($user_name, $password);            
			if (!$user_id)
            {
                /* 未通过验证，提示错误信息 */
                $this->show_warning($ms->user->get_error());
                return;
            }else{
                /* 通过验证，执行登陆操作 */
                $this->_do_login($user_id);
				
            }
			header('location:index.php?app=member');
			exit();

//			if ( $_POST['ret_url'] )//登录成功后返回来源页
//			{
//				header('location:'.rawurldecode($_POST['ret_url']));
//			}else{
//				
//			}			
        }
    }


    /**
     *    注册一个新用户
     *
     *    @author    Garbin
     *    @return    void
     */
    function register()
    {
        if ($this->visitor->has_login)
        {
            $this->show_warning('has_login', '进入会员中心', 'index.php?app=member');

            return;
        }
        if (!IS_POST)
        {
            if (!empty($_GET['ret_url']))
            {
                $ret_url = htmldecode($_GET['ret_url']);
            }else{
                if (isset($_SERVER['HTTP_REFERER']))
                {
                    $ret_url = $_SERVER['HTTP_REFERER'];
                }else{
                    $ret_url = site_url() . '/index.php';
                }
            }
            $this->assign('ret_url', rawurlencode($ret_url));

            /* 导入jQuery的表单验证插件 */
            $this->import_resource('jquery.plugins/jquery.validate.js');
			$this->_config_seo('title', '用户注册 - ' . Conf::get('site_name'));
			$this->assign('curitem', '用户注册');	
            $this->display('member.register.html');
        }
        else
        {
            /* 注册并登陆 */
            $user_name = trim($_POST['user_name']);
            $password  = trim($_POST['password']);
			$phone_mob = trim($_POST['phone_mob']);
            $passlen = strlen($password);
            $user_name_len = strlen($user_name);
            if ($user_name_len < 3 || $user_name_len > 25)
            {
                $this->show_warning('user_name_length_error');
                return;
            }
            if ($passlen < 6 || $passlen > 20)
            {
                $this->show_warning('password_length_error');
                return;
            }

            $ms =& ms(); //连接用户中心
            $user_id = $ms->user->register($user_name, $password, $email);
            if (!$user_id)
            {
                $this->show_warning($ms->user->get_error());
                return;
            }
			//如果用户填写了手机号码，为该会员写入手机号码
			if ( $phone_mob )
			{
				$model_member =& m('member');
				$model_member->edit("user_id = '{$user_id}'", array( 'phone_mob' => $phone_mob ));				
			}

            //登录
            $this->_do_login($user_id);
			
            header('location:index.php?app=member');
			exit();
			/*注册成功后提示用户用户去哪里*/
			if ( strpos($_POST['ret_url'],'cart') )//注册成功后返回购物页面
			{
				header('location:'.rawurldecode($_POST['ret_url']));
			}else{
				header('location:index.php?app=member');
			}
			//header('location:index.php?app=member&act=register_ok&ret_url='.$_POST['ret_url']);
        }
    }


    /* 执行登录动作 */
    function _do_login($user_id)
    {
        $mod_user =& m('member');
        $user_info = $mod_user->get(array(
            'conditions'    => "user_id = '{$user_id}'",
            'join'          => 'has_store',                 //关联查找看看是否有店铺
            'fields'        => 'user_id, user_name, reg_time, last_login, last_ip, store_id',
        ));

        /* 分派身份 */
        $this->visitor->assign($user_info);

        /* 更新用户登录信息 */
        $mod_user->edit("user_id = '{$user_id}'", "last_login = '" . gmtime()  . "', last_ip = '" . real_ip() . "', logins = logins + 1");

//        /* 更新购物车中的数据 */
//        $mod_cart =& m('cart');
//        $my_store = empty($user_info['store_id']) ? 0 : $user_info['store_id'];/* 店铺ID */
//        $mod_cart->edit("(user_id = '{$user_id}' OR session_id = '" . SESS_ID . "') AND store_id <> '{$my_store}'", array(
//            'user_id'    => $user_id,
//            'session_id' => SESS_ID,
//        ));
//
//        /* 去掉重复的项 */
//        $cart_items = $mod_cart->find(array(
//            'conditions'    => "user_id='{$user_id}' GROUP BY spec_id",
//            'fields'        => 'COUNT(spec_id) as spec_count, spec_id, rec_id',
//        ));
//        if (!empty($cart_items))
//        {
//            foreach ($cart_items as $rec_id => $cart_item)
//            {
//                if ($cart_item['spec_count'] > 1)
//                {
//                    $mod_cart->drop("user_id='{$user_id}' AND spec_id='{$cart_item['spec_id']}' AND rec_id <> {$cart_item['rec_id']}");
//                }
//            }
//        }
    }
	
    /**
     *    检查用户是否存在
     *
     *    @author    Garbin
     *    @return    void
     */
    function check_user()
    {
        $user_name = empty($_GET['user_name']) ? null : htmldecode($_GET['user_name']);
        if (!$user_name)
        {
            echo ecm_json_encode(false);

            return;
        }
        $ms =& ms();

        echo ecm_json_encode($ms->user->check_username($user_name));
    }
    /**
     *    修改基本信息
     *
     *    @author    Hyber
     *    @usage    none
     */
    function profile()
	{
        $user_id = $this->visitor->get('user_id');
        if (!IS_POST)
        {
            $model_user =& m('member');
            $profile    = $model_user->get_info(intval($user_id));
            $this->assign('profile',$profile);
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,res:style/mobile_date_input.js', 'style' =>  'res:style/css_mobile_date.css'));			
            $this->_config_seo('title', Lang::get('my_profile') . ' - ' . Lang::get('member_center'));
            $this->assign('curitem', Lang::get('my_profile'));
			$this->display('member.profile.html');
        }
        else
        {
            $data = array(
                'real_name' => htmldecode($_POST['real_name']),
                'gender'    => htmldecode($_POST['gender']),
                'birthday'  => htmldecode($_POST['birthday']),
                'im_qq'     => htmldecode($_POST['im_qq']),
                'phone_mob' => htmldecode($_POST['phone_mob']),
				'phone_tel' => htmldecode($_POST['phone_tel']),
				'idpic' => htmldecode($_POST['idpic']),
            );

            $model_user =& m('member');
            $model_user->edit($user_id , $data);
            if ($model_user->has_error())
            {
                $this->show_warning($model_user->get_error());
                return;
            }
			$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '修改个人资料', 0);//添加操作日志	

            $this->show_message('edit_profile_successed');
        }
    }	
    /**
     *    修改密码
     *
     *    @author    Hyber
     *    @usage    none
     */
    function password(){
        $user_id = $this->visitor->get('user_id');
        if (!IS_POST)
        {
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));
            $this->_config_seo('title', '修改密码 - ' . Conf::get('site_name'));
			$this->assign('curitem', '修改密码');				
            $this->display('member.password.html');
        }
        else
        {
            /* 两次密码输入必须相同 */
            $orig_password      = $_POST['password'];
            $new_password       = $_POST['new_password'];
            $confirm_password   = $_POST['confirm_password'];
            if ($new_password != $confirm_password)
            {
                $this->show_warning('新密码和确认新密码不一致');
                return;
            }
            if (!$new_password)
            {
                $this->show_warning('新密码不能为空');
                return;
            }
            $passlen = strlen($new_password);
            if ($passlen < 6 || $passlen > 20)
            {
                $this->show_warning('新密码长度应在6-20个字符之间');
                return;
            }

            /* 修改密码 */
            $ms =& ms();    //连接用户系统
            $result = $ms->user->edit($this->visitor->get('user_id'), $orig_password, array(
                'password'  => $new_password
            ));
            if (!$result)
            {
                /* 修改不成功，显示原因 */
                $this->show_warning($ms->user->get_error());
                return;
            }
			$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '【手机】修改密码', 0);//添加操作日志	

            $this->show_message('密码修改成功','会员中心', 'index.php?app=member');
        }
    }

    /**
     * 构造15位的随机字符串
     *
     * @return string | 生成的字符串
     */
    function _rand()
    {
        $word = $this->generate_code();
        return $word;
    }

    function generate_code($len = 15)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0, $count = strlen($chars); $i < $count; $i++)
        {
            $arr[$i] = $chars[$i];
        }

        mt_srand((double) microtime() * 1000000);
        shuffle($arr);
        $code = substr(implode('', $arr), 5, $len);
        return $code;
    }	

}
?>